from django.db.models import Q
from rest_framework.views import APIView
from app01.models import IDCDevice, Client, Cabinet, MachineRoom
from django.http import JsonResponse
from app01.Baseview import BasedAPIView


class ClientView(BasedAPIView):
    def get(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'get_client_all':
            return self.get_client_all(request)
        if module == 'get_options':
            return self.get_options(request)

    def post(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'add':
            return self.add(request)
        if module == 'edit':
            return self.edit(request)
        if module == 'dele':
            return self.dele(request)

    def get_options(self, request):
        clients = Client.objects.all()
        options = {
            'clients': [
                {
                    'id': client.id,
                    'name': client.client_name,
                    'abbr': client.client_abbreviation
                }
                for client in clients
            ]
        }
        return super().success(data=options)

    def get_client_all(self, request, format=None):
        page = int(request.GET.get('page', 1))
        pagesize = int(request.GET.get('pagesize', 10))
        uid = request.GET.get('id', None)
        client_abbr = request.GET.get('client_abbr', None)
        client_name = request.GET.get('client_name', None)
        query = Q()
        if uid is not None:
            query &= Q(id=uid)
        if client_name is not None:
            query &= Q(client_name__icontains=client_name)
        if client_abbr is not None:
            query &= Q(client_abbreviation__icontains=client_abbr)

        clients = Client.objects.filter(query)
        total = clients.count()
        client_dic = []
        for item in clients:
            values = {
                'id': item.id,
                'client_name': item.client_name,
                'client_abbr': item.client_abbreviation
            }
            client_dic.append(values)
        #分页处理
        start_page = page * pagesize - pagesize
        end_page = page * pagesize
        paginated_data = client_dic[start_page:end_page]

        res_data = {
            'total': total,
            'data': paginated_data
        }
        return super().success(data=res_data)

    def add(self, request):
        client_name = request.data.get('client_name')
        client_abbreviation = request.data.get('abbr_name')
        client_remarks = request.data.get('remarks')

        try:
            client = Client(client_name=client_name, client_abbreviation=client_abbreviation, remarks=client_remarks)
            client.save()
            data = {
                'id': client.id,
                'client_name': client.client_name,
                'abbr_name': client.client_abbreviation,
                'remarks': client.remarks
            }

            return super().success(msg="新增成功", data=data)
        except Exception as e:
            return super().error(msg=str(e))

    def edit(self, request):
        uid = request.data.get('id', None)
        if uid:
            client = Client.objects.get(id=uid)
            client.client_name = request.data.get('client_name', client.client_name)
            client.client_abbreviation = request.data.get('client_abbr', client.client_abbreviation)
            client.remarks = request.data.get('remarks', client.remarks)
            client.save()
            data = {
                'id': client.id,
                'client_name': client.client_name,
                'abbr_name': client.client_abbreviation,
                'remarks': client.remarks
            }
            return super().success(msg="更新成功", data=data)
        else:
            return super().warn(msg="修改数据出现异常")

    def dele(self, request):
        '''删除数据'''
        ids = request.data.get("id", "")
        if ids == "":
            return super().error(msg="ID不能为空")
        ids = ids.split(",")  # 将字符串切割为列表
        ids_int = []
        for i in ids:
            if i == "":
                continue
            ids_int.append(int(i))  # 将id转换为数字类型 然后添加到新的列表中
        Obj = Client.objects.filter(id__in=ids_int)  # id__in为 根据id字段 传入一个列表 批量查询需要删除的数据
        if not Obj.exists():  # 检测数据是否存在
            return super().error(msg="数据不存在")
        Obj.delete()  # 删除查询到的数据
        return super().success(msg="删除成功")
